<template>
  <div class="boxsty zhiBiao">
    <div :height="searchheight" v-if="showSearch">
      <span style="float:right;margin-top: -30px;cursor: pointer;" @click="searchchangeadvanced">
        {{ searchadvanced ? "收起" : "展开" }}
        <i
          :class="searchadvanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
        />
      </span>
      <div v-show="searchadvanced" v-if="tianBaoTable.lastPage=='zbnd'">
        <el-form
          :inline="true"
          :model="dataForm"
          @keyup.enter.native="getDataList()"
          class="form-inline"
          v-if="showSearch"
        >
          <el-form-item label>
            <el-checkbox-group v-model="dataForm.check">
              <el-checkbox
                v-for="item in checkList"
                :key="item.name"
                :label="item.name"
              >{{item.name}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div style="float: right">
      <el-button
        type="primary"
        plain
        :disabled="dataList.length==0"
        @click="saveZhibiaoData"
        v-if="editFlag == 1"
      >保存</el-button>
      <el-button type="primary" plain @click="fnBackOldPage">关闭</el-button>
    </div>
    <div class="avue-crud">
      <el-table
        ref="zhibiaotable"
        style="width: 100%;margin-top:20px"
        :data="dataList"
        border
        v-loading="dataListLoading"
      >
        <el-table-column
          v-if="tianBaoTable.lastPage=='zbnd'"
          label="选择"
          type="selection"
          width="55"
        ></el-table-column>
        <el-table-column type="index" width="60" header-align="center" align="center" label="序号"></el-table-column>
        <el-table-column
          v-if="radio =='1'"
          prop="assessRealName"
          header-align="center"
          align="center"
          min-width="100"
          label="被考核对象"
        >
          <template slot="header">
            <span>被考核对象</span>
            <span class="mg-l10">({{dataList.length}})</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="radio =='2'"
          prop="assessDeptName"
          header-align="center"
          align="center"
          min-width="100"
          label="机构名称"
        >
          <template slot="header">
            <span>机构名称</span>
            <span class="mg-l10">({{dataList.length}}个)</span>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item,index) in list"
          :key="index"
          align="center"
          :label="item.name"
        >
          <template slot="header">
            <span>{{ item.name }}</span>
            <!--<span class="mg-l10">({{dataList|filterNum(item,index)}}个)</span>-->
          </template>

          <el-table-column header-align="center" align="center" min-width="100" label="目标值">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.itemList[index].id!==null"
                :rows="1"
                type="textarea"
                v-model="scope.row.itemList[index].targetValue"
                @blur="getColumnMbz(scope.row, scope.$index,index)"
                placeholder="目标值"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column header-align="center" align="center" min-width="100" label="权重">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.itemList[index].id!==null"
                v-model="scope.row.itemList[index].weight"
                oninput="value=value.replace(/[^\d.]/g, '').replace(/^\./g, '').replace(/\.{2,}/g, '.').replace(/(\.\d+)\./g, '$1').replace(/^0+(\d)/, '$1').replace(/(\d{15})\d*/, '$1').replace(/(\.\d{2})\d*/, '$1')"
                @blur="getColumnQz(scope.row, scope.$index,index)"
                placeholder="权重"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column header-align="center" min-width="100" align="center" label="单位">
            <template slot-scope="scope">
              <span>{{scope.row.itemList[index].unit}}</span>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  indexExaminDataList,
  indexExaminTabList,
  newIndexExaminTabList
} from "@/api/dailyExamine/targetExamine/indicatorFormulation";
import { resultFillSave } from "@/api/dailyExamine/targetExamine/InitiateFilling";
import { validatenull } from "@/util/validate"; //判断空

export default {
  props: {
    tianBaoTable: {},
    ids: [],
    lastPage: "",
    hetongzhibiaoTable: {},
    dataListHT: [],
    radio: "",
    ndids: []
  },
  data() {
    return {
      editFlag: 1,
      pageTitle: "业绩合同",
      dataForm: {
        check: []
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      addOrUpdateVisible: false,
      fullscreenLoading: false,
      zhiShow: "1",
      zhibiaoForm: {},
      showSearch: true,
      showBackBtn: true,
      checkList: [],
      idArray: "",
      searchadvanced: true,
      searchheight: "0",
      list: []
    };
  },
  watch: {
    "dataForm.check"(newValue, oldValue) {
      if (newValue.length > 0) {
        this.idArray = "";
        // newValue.forEach(ele => {
        //   this.idArray = this.idArray + ele + ",";
        // });
        this.list = this.checkList.filter(x => {
          return newValue.some(y => {
            return x.name == y;
          });
        });
        newValue.forEach(ele => {
          this.checkList.map(it => {
            if (it.name == ele) {
              this.idArray = this.idArray + it.itemIdList.toString() + ",";
            }
          });
        });
        this.getDataList();
      }
      if (newValue.length == 0) {
        this.list = [];
        this.dataList = [];
        //console.log(oldValue)
      }
    }
  },
  filters: {
    filterNum(dataList, listItem, index) {
      var num = 0;
      var arr = dataList.filter(item => {
        return item["zbId" + (index + 1)];
      });
      num = arr.length;
      return num;
    }
  },
  created() {
    var ids = this.ids;
    var params = {
      ids: this.ids
    };
    console.log(this.radio);
    this.getZhibiaoCheckndData(ids);

    //this.getDataList()
  },
  computed: {
    ...mapGetters(["permissions"])
  },
  methods: {
    getColumnQz(row, index,hindex){
      //console.log(row,index,hindex)
      if(row !=null && row !="") {
        let data = [];
        data = this.$refs.zhibiaotable.selection;
        if(data.length != 0){
          let  checked = [];
          let  inputId = '';
          let  weighted =''
          row.itemList.forEach((item,index1) =>{
            if(index1 == hindex){
              inputId = item.id;
              weighted = item.weight
            }
          })
          console.log('输入框的id：：',inputId)
          data.forEach((item2,index2) => {
            item2.itemList.forEach((item3,index3) =>{
              if(index3 == hindex){
                checked.push(item3.id);
              }
            })
          });
          console.log('选中的id：：',checked)
          data.forEach((item4) => {
            if(checked.includes(inputId)){
              item4.itemList.forEach((item5,index5) =>{
                if(index5 == hindex){
                  if(weighted != '' && weighted !=null){
                    item5.weight = weighted
                  }
                }
              })
            }
          });
          this.$forceUpdate()
        }
      }
    },
    getColumnMbz(row, index,hindex){
      //console.log(row,index,hindex)
      if(row !=null && row !="") {
        let data = [];
        data = this.$refs.zhibiaotable.selection;
        if(data.length != 0){
          let  checked = [];
          let  inputId = '';
          let  targetValueed =''
          row.itemList.forEach((item,index1) =>{
            if(index1 == hindex){
              inputId = item.id;
              targetValueed = item.targetValue
            }
          })
          console.log('输入框的id：：',inputId)
          data.forEach((item2,index2) => {
            item2.itemList.forEach((item3,index3) =>{
              if(index3 == hindex){
                checked.push(item3.id);
              }
            })
          });
          console.log('选中的id：：',checked)
          data.forEach((item4) => {
            if(checked.includes(inputId)){
              item4.itemList.forEach((item5,index5) =>{
                if(index5 == hindex){
                  if(targetValueed != '' && targetValueed !=null){
                    item5.targetValue = targetValueed
                  }
                }
              })
            }
          });
          this.$forceUpdate()
        }
      }
    },
    saveZhibiaoData() {
      let temp = this.dataList.map(it => {
        return it.itemList;
      });
      var result = [];
      for (var i = 0; i < temp.length; i++) {
        for (var j = 0; j < temp[i].length; j++) {
          if (temp[i][j].id !== null) {
            result.push(temp[i][j]);
          }
        }
      }

        const szValid = /^[0-9]*$/;
        let flagWeight = result.every( it=> {
            return !validatenull(it.weight)
        }) ;
        if(!flagWeight){
            this.$message.error('权重不可为空');
            return ;
        }

        //验证是否超200字
        let flagTargetValue = result.every( it=> {
            return !validatenull(it.targetValue) && it.targetValue.length<=200 ;
        }) ;
        if (!flagTargetValue){
            this.$message.error('目标值不可为空且不可超过200字');
            return ;
        }

      resultFillSave(result).then(response => {
        this.$message.closeAll();
        this.$message.success("保存成功");
        this.getDataList();
        this.fnBackOldPage();
      });
    },

    getZhibiaoCheckndData(ids) {
      indexExaminDataList(ids.toString()).then(response => {
        this.checkList = response.data.data;
        if (this.tianBaoTable.lastPage != "zbnd") {
          //this.list = this.checkList;
          //上面这种会出现重复的情况，所以用id去取了值（去重）
          var arr = response.data.data;
          this.list = [];
          arr.forEach(item => {
            var obj = this.list.find(listItem => listItem.id == item.id);
            if (!obj) {
              this.list.push(item);
            }
          });

          new Promise((resolve, reject) => {
            response.data.data.forEach(ele => {
              //console.log(ele)
              this.idArray = this.idArray + ele.id + ",";
            });
            resolve(this.getDataList());
          });
        } else {
          // response.data.data.forEach(ele=>{
          //   //console.log(ele)
          //     this.idArray = this.idArray + ele.id+',';
          // })
          this.list = [];
        }
      });
    },
    searchchangeadvanced() {
      this.searchadvanced = !this.searchadvanced;
      if (this.searchadvanced) {
        this.searchheight = "auto";
      }
    },
    //复选框选中数据时批量更改目标值
    fnChangeMuB(val, prop, index, isEdit) {
      //console.log(val,prop,index,isEdit)
      //zhibiaotable
      var selectedData = this.$refs.zhibiaotable.selection;
      //console.log(selectedData)
      if (selectedData.length > 0) {
        selectedData.forEach(item => {
          if (item[isEdit]) {
            item[prop] = val;
          }
        });
      }
      this.saveZhibiaoData();
    },
    init(data) {
      this.lastPage = data.lastPage;
      this.showSearch = data.showSearch;
      this.pageTitle = data.pageTitle;
      this.showBackBtn = data.showBackBtn;
    },
    // 获取数据列表
    getDataList() {
      this.dataList = [] ; //解决table重新布局列渲染错位bug
      this.dataListLoading = true;
      var params = {
        zhibiaoId: this.idArray,
        str: 1,
        ids: this.ids,
        typestr: this.tianBaoTable.lastPage,
        ndIds: this.ndids
      };
      newIndexExaminTabList(this.ids.toString(), this.idArray.toString()).then(
        response => {
          this.dataList = response.data.data;
          this.dataListLoading = false;
        }
      );
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id);
      });
    },

    //子集信息
    zhibiaoChild(zhibiaoChild) {
      if (zhibiaoChild) {
        this.zhiShow = 1;
      }
    },
    //新增子集返回的数据(关闭修改页面，打开指标库维护)
    openZhibiao(data) {
      this.addOrUpdateVisible = false;
      this.zhiShow = 2;
      this.zhibiaoForm = {
        enter: 0,
        disabled: false
      };
    },
    //返回原来的页面
    fnBackOldPage() {
      this.$emit("fnBackOldPage", "返回原页面");
    },
    editLock() {
      this.editFlag = 0;
    }
  }
};
</script>
